﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Ebc.DesignerDsl.CustomCode
{
    public class UsingsParser
    {
        public UsingTypeDefinition Parse(string fullCSharpType, Type typeInstance)
        {
            IEnumerable<string> usings = this.BuildUsings(typeInstance);
            string result = fullCSharpType.Replace(" ", string.Empty);

            foreach (var item in usings)
            {
                result = result.Replace(item + ".", string.Empty);
            }

            return new UsingTypeDefinition()
            {
                CSharpType = result,
                Usings = usings
            };
        }

        private IEnumerable<string> BuildUsings(Type rootType)
        {
            var result = new List<string>();

            if (!result.Contains(rootType.Namespace))
            {
                result.Add(rootType.Namespace);
            }

            if (rootType.IsGenericType)
            {
                foreach (var item in rootType.GetGenericArguments())
                {
                    foreach (var paramUsing in this.BuildUsings(item))
                    {
                        if (!result.Contains(paramUsing))
                        {
                            result.Add(paramUsing);
                        }
                    }
                }
            }

            return result;
        }
    }

    public class UsingTypeDefinition
    {
        public IEnumerable<string> Usings { get; set; }
        public string CSharpType { get; set; }
    }
}